package com.stlm2.dems.dao.impl;

import com.stlm2.dems.entity.DdmGoods;
import com.stlm2.dems.entity.User;
import org.springframework.stereotype.Repository;

import com.stlm2.dems.entity.FootMark;
import com.stlm2.dems.dao.FootMarkDao;
import com.stlm2.core.base.impl.BaseDaoImpl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository("footMarkDao")
public class FootMarkDaoImpl extends BaseDaoImpl<FootMark> implements FootMarkDao {

    @Override
    public List<FootMark> getByGoodsId(Integer userId, Integer goodsId) {
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("goodsId",goodsId);
        map.put("userId",userId);
        return selectList("getByGoodsId",map);
    }

    @Override
    public Integer getCount(Integer userId) {
        return  (Integer) _selectOne("getCount",userId);
    }

    //修改状态为 前台不显示
    @Override
    public void updateByUserId(Integer userId) {
        update("updateByUserId",userId);
    }

   //添加或修改 我的足迹
    public void addFootMark(User user, DdmGoods goods){
        if (user==null||goods==null){
            return ;
        }
        List<FootMark> old=getByGoodsId(user.getId(),goods.getId());
        int num=1;
        if (old!=null&&old.size()>0){//该用户已浏览过该商品
            if(old.size()==1){
                FootMark footMark=old.get(0);
                num+=footMark.getNum();
                footMark.setNum(num);
                footMark.setState(true);
                footMark.setModifyTime(new Date());
                modify(footMark);
            }else {//数据错误，该商品记录被重复添加， 在此修正
                Date firstTime=new Date();
                for (FootMark footMark:old) {
                    num+=footMark.getNum();
                    firstTime=footMark.getCreateTime();
                    delete(footMark.getId());
                }
                FootMark footMark=new FootMark();
                footMark.setUserId(user.getId());
                footMark.setGoodsId(goods.getId());
                footMark.setCreateTime(firstTime);
                footMark.setState(true);
                footMark.setNum(null);
                footMark.setModifyTime(new Date());
                add(footMark);
            }
        }else {//第一次浏览该商品
            FootMark footMark=new FootMark();
            footMark.setUserId(user.getId());
            footMark.setGoodsId(goods.getId());
            footMark.setCreateTime(new Date());
            footMark.setState(true);
            footMark.setNum(num);
            footMark.setModifyTime(new Date());
            add(footMark);
        }
    }

    @Override
    public Integer sumNum(Integer goodsId) {
        return (Integer) _selectOne("sumNum",goodsId);
    }
}